package com.rock.drawboard.thread;

import android.util.Log;

import com.rock.drawboard.MyApplication;
import com.rock.drawboard.constant.EventConfig;
import com.rock.drawboard.event.LoginEvent;
import com.rock.drawboard.module.DataPackage;
import com.rock.drawboard.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

/**
 * 客户端 - 发送 - 数据
 */
public class ClientSendThread extends Thread {

    static Socket socket = null;
    static ObjectOutputStream output;

    public static void sendDataPackage(DataPackage dp) {

        if (!MyApplication.isServer && socket != null && !socket.isClosed() && output != null) {
            try {
                LogUtils.e("LoginActivity2- ClientSendThread", dp.getType().toString());
                output.writeObject(dp);
                output.flush();
                LogUtils.e("LoginActivity2- ClientSendThread", "DataPackage - ok");
            } catch (IOException e) {
                e.printStackTrace();
                LogUtils.e("LoginActivity2- ClientSendThread", "DataPackage - IOException");
            }

        } else {
            LogUtils.e("LoginActivity2- ClientSendThread", "socket.isClosed");
        }
    }

    @Override
    public void run() {
        try {
            // 连接服务器 并设置连接超时为5秒
                if (socket == null) {
                    socket = new Socket();
                }
                if (!socket.isConnected()) {
                    socket.connect(new InetSocketAddress(MyApplication.server_ip, 30000), 1000);
                    output = new ObjectOutputStream(socket.getOutputStream());
                    LogUtils.e("LoginActivity2- ClientSendThread", "!socket.isConnected");
                }

            LogUtils.e("LoginActivity2- ClientSendThread", "output");

        } catch (SocketTimeoutException e) {
            LogUtils.e("LoginActivity2- ClientSendThread", "SocketTimeoutException");
            doException();
        } catch (IOException e) {
            LogUtils.e("LoginActivity2- ClientSendThread", "IOException");
            doException();
        }
    }

    private void doException() {
        EventBus.getDefault().post(new LoginEvent(EventConfig.LOGIN_ERROR));
    }

}
